package com.xingkeduo.dao.database;

import java.lang.reflect.Method;

import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;
import org.springframework.stereotype.Component;

import com.xingkeduo.util.pojo.base.BaseQuery;
import com.xingkeduo.util.pojo.base.BaseTable;

@Component
public class DatabaseProxy<T extends BaseTable<T>, Q extends BaseQuery<Q>> implements MethodInterceptor {
	// 给目标对象创建一个代理对象
	public DatabaseAccessObject<T, Q> build(SqlSessionTemplate sqlSessionTemplate) {
		// 1.工具类
		Enhancer en = new Enhancer();
		// 2.设置父类
		en.setSuperclass(DatabaseAccessObject.class);
		// 3.设置回调函数
		en.setCallback(this);

		Class[] paramClasses = { SqlSessionTemplate.class};
		Object[] paramInstances = { sqlSessionTemplate };
		DatabaseAccessObject<T, Q> dao = (DatabaseAccessObject<T, Q>) en.create(paramClasses, paramInstances);
		// 4.创建子类(代理对象)
		return dao;
	}

	/**
	 * 回调方法
	 */
	@Override
	public Object intercept(Object arg0, Method arg1, Object[] arg2, MethodProxy arg3) throws Throwable {
		return arg3.invokeSuper(arg0, arg2);
	}
}
